package statistics

import (
	"github.com/wcharczuk/go-chart/v2"
	"os"
	"path/filepath"
	"sync"
)

type Chart struct {
	X     []float64
	Y     map[string][]float64
	mutex sync.RWMutex
}

var ChartObj = &Chart{
	X: make([]float64, 0),
	Y: map[string][]float64{
		"PROCESSING": make([]float64, 0),
		"THREADING":  make([]float64, 0),
		"SUCCESS":    make([]float64, 0),
		"FAIL":       make([]float64, 0),
		"QPS":        make([]float64, 0),
		"AVG_TIME":   make([]float64, 0),
	},
	mutex: sync.RWMutex{},
}

func (c *Chart) add(stamp float64, data map[string]float64) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	c.X = append(c.X, stamp)
	for k, v := range data {
		c.Y[k] = append(c.Y[k], v)
	}
}

func (c *Chart) createPng() {
	// 创建一个图表对象
	graph := chart.Chart{
		XAxis: chart.XAxis{
			Name:      "Time",
			NameStyle: chart.Style{},
		},
		YAxis: chart.YAxis{
			Name:      "Data",
			NameStyle: chart.Style{},
		},
		Series: []chart.Series{},
	}

	for s, float64s := range c.Y {
		graph.Series = []chart.Series{
			chart.ContinuousSeries{
				Name:    s,
				XValues: c.X,
				YValues: float64s,
			},
		}
		// 保存图表到文件
		f, _ := os.Create(filepath.Join("png", s+".png"))
		_ = graph.Render(chart.PNG, f)
		_ = f.Close()
	}
}
